# -*- coding: ascii -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
#
# notedown - a wrapper around markdown (pretty html from text)
# Copyright (C) 2008  Chris Clark
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import re

# TODO also look at http://devsuki.com/pottymouth/ - renamed for pep8
# TODO onlyimport one, if that fails, try the next one.
import markdown # from http://sourceforge.net/projects/python-markdown
import markdown2 # from http://code.google.com/p/python-markdown2/ -- it is faster

markdown_func = markdown.markdown
#markdown_func = markdown2.markdown

AUTO_LINK_RE = re.compile(r"""
                        (                          # leading text
                          <\w+.*?>|                # leading HTML tag, or
                          [^=!:'"/]|               # leading punctuation, or 
                          ^                        # beginning of line
                        )
                        (
                          (?:https?://)|           # protocol spec, or
                          (?:www\.)                # www.*
                        ) 
                        (
                          [-\w]+                   # subdomain or domain
                          (?:\.[-\w]+)*            # remaining subdomains or domain
                          (?::\d+)?                # port
                          (?:/(?:(?:[~\w\+%-]|(?:[,.;:][^\s$]))+)?)* # path
                          (?:\?[\w\+%&=.;-]+)?     # query string
                          (?:\#[\w\-]*)?           # trailing anchor
                        )
                        ([\.,"'?!;:]|\s|<|$)       # trailing text
                           """, re.X)
## from http://pylonshq.com/WebHelpers/webhelpers/rails/text.py.html
# I have my own "hilight() routine as the Rails one does not handle regex or html tags
#def auto_link_urls(text, **href_options):
def auto_link_urls(text):
    # FIXME BUG only does single link per line - should be in markdown anyway....
    #extra_options = tag_options(**href_options)
    def handle_match(matchobj):
        all = matchobj.group()
        a, b, c, d = matchobj.group(1, 2, 3, 4)
        if re.match(r'<a\s', a, re.I):
            return all
        text = b + c
        if b == "www.":
            b = "http://www."
        #return '%s<a href="%s%s"%s>%s</a>%s' % (a, b, c, extra_options, text, d)
        return '%s<a href="%s%s">%s</a>%s' % (a, b, c, text, d)
    return re.sub(AUTO_LINK_RE, handle_match, text)

def auto_escape_slashes(text):
    """Automatically turn '\' into '\\' (or possible quote with backtick ` for markdown"""
    ###
    """Did briefly look at doing his with regex:
    
        match all slashes:
            \\
            
        match all strings containing slash(es) NOTE too greedy:
            \S*\\\S*
            
        match all strings containing slash(es) (not in indentd text) NOTE too greedy:
            ^(?!\s).*\S*\\\S*


        Only  matches ` quotes:

            `.+\\.+`
            
            
        does not handle ` quotes
            ^(?!\s).+\\
            ^(?!\s).*\\
    being lazy and slow do this by hand...
    """
    result = []
    for line in text.split('\n'):
        if line.startswith('\t') or line.startswith('    '):
            result.append(line)
        else:
            result.append(line.replace('\\', '\\\\')) ## WARNING screws up backticked text, e.g.: `c:\some'path`
        result.append('\n')
    return ''.join(result)
    
def auto_newline(text, line_length_cut_point=60):
    """Automatically turn short lines into <br>"""
    result = []
    for line in text.replace('\r', '').split('\n'):
        if line.startswith('\t') or line.startswith('    '):
            result.append(line)
        else:
            result.append(line)
            if 1 < len(line) <= line_length_cut_point:
                result.append('  ')
        result.append('\n')
    return ''.join(result)
    
def mymarkdown(in_str, make_pretty=True, firstline_title=True):
    pretty_html = """
<STYLE TYPE="text/css">

<!--
body {
    font-family: verdana;
}
pre {
    background-color: lightgrey;
    border: 1px solid #5096B9;
    padding: 10 10 10 10;
}
h1 {
    background-color: #5096B9;
    color: white;
    padding: 10 10 10 10;
    text-align: center;
}
h2 {
    color: #5096B9;
}
h3 {
    color: #5096B9;
}
h4 {
    color: #5096B9;
}
h5 {
    color: #5096B9;
}
h6 {
    color: #5096B9;
}
span.error {
    color: #ff0000;
}
label.required {
    color: #0000ff;
}
-->

</STYLE>

""" # NOTE missing html end tag and body
    ##TODO add html and body tags!
    result=[]
    result.append('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">')
    result.append('<html>')
    result.append('<head>')
    result.append('<meta http-equiv="Content-Type" content="text/html; charset=utf-8">') ## TODO check, markdown2 appears to use utf8...
    if make_pretty:
        result.append(pretty_html)
    # done below...
    #if firstline_title:
    #    in_str = '#' + in_str
    result.append('<title>Temp markdown note</title>')
    result.append('</head>')
    
    ## TODO table of contents
    ## TODO footnotes
    ## auto hyperlink if missing <>
    ## Assume first line is title so "header" it
    temp_str = auto_link_urls(in_str)
    temp_str = auto_escape_slashes(temp_str)
    temp_str = auto_newline(temp_str)
    result.append('<body>')
    result.append(markdown_func('#'+temp_str))
    result.append('</body>')
    result.append('</html>')
    return ''.join(result)
    
